package com.tl.web02.controller.common_servlet;

import com.tl.web02.config.Config;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(!notNullVerify(username)){
            excuteJs(out,"用户名不可以为空",Config.VERSION+"login.jsp");
        }
        if(!notNullVerify(password)){
            excuteJs(out,"密码不可以为空",Config.VERSION+"login.jsp");
        }
        HashMap<String,String> userMap = (HashMap<String,String>)getServletContext().getAttribute("userMap");

        //判断用户名和密码是否有
        String auth = userMap.get(username);
        if(auth==null){
            System.out.println("用户名不存在");
            excuteJs(out,"用户名不存在,请注册",Config.VERSION+"register.jsp");
            return;
        }else{
            if(!auth.equals(password)){
                System.out.println("密码错误");
                String msg = "密码错误,请重新输入";
                String nextAction = Config.VERSION+"login.jsp";
                excuteJs(out,msg,nextAction);
                return;
            }
            System.out.println("登录成功");
            String msg = "登录成功";
            String nextAction = Config.VERSION+"index.jsp";
            excuteJs(out,msg,nextAction);
        }
    }
    public void excuteJs(PrintWriter out,String msg,String action){
        String jsScript = "alert('"+msg+"');window.location.href='"+action+"'";
        System.out.println(jsScript);
        out.println("<script language=\"javascript\">"+jsScript+"</script>");
        out.flush();
        out.close();
    }
    public boolean notNullVerify(String str){
        if(str==null||str.trim().length()==0){
            return false;
        }
        return true;
    }
}
